package cn.com.nes.site.listener;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;

import java.math.BigDecimal;
import java.text.ParseException;

public class BigDecimalConverter implements Converter<BigDecimal> {

    @Override
    public Class<BigDecimal> supportJavaTypeKey() {
        return BigDecimal.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public BigDecimal convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                        GlobalConfiguration globalConfiguration) throws ParseException {
        try {
            // 获取单元格类型
            final CellDataTypeEnum cellDataType = cellData.getType();
            // 如果是数字类型
            if (CellDataTypeEnum.NUMBER == cellDataType) {
                return cellData.getNumberValue();
            } else if (CellDataTypeEnum.EMPTY == cellDataType) {
                return null;
            } else if (CellDataTypeEnum.BOOLEAN == cellDataType) {
                return cellData.getBooleanValue() ? BigDecimal.ONE : BigDecimal.ZERO;
            } else if (CellDataTypeEnum.ERROR == cellDataType) {
                return null;
            } else if (CellDataTypeEnum.DATE == cellDataType) {
                return null;
            } else {
                final String stringValue = cellData.getStringValue();
                if (NumberUtil.isNumber(stringValue)) {
                    return NumberUtils.parseBigDecimal(stringValue, contentProperty);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        return NumberUtils.formatToCellDataString(value, contentProperty);
    }
}
